<template>
    <div class="duty">
        <div class="duty-top">
            <div class="duty-top-left">
                <div class="duty-top-left-top">
                    <a-tabs class="top-tab" v-model:activeKey="deptActiveKey" @change="handleTab">
                        <a-tab-pane v-for="item in deptList"  :key="item.value" :disabled="userStore.getLoginInfo?.userInfo?.orgCode!=item.value" :tab="item.label">
                        </a-tab-pane>
                        <!-- <a-tab-pane key="1" tab="管制部">
                        </a-tab-pane>
                        <a-tab-pane key="2" tab="运行部" force-render></a-tab-pane> -->
                        <template #rightExtra>
                            <span>全部分组：</span><a-switch checked-children="开" @change="switchhandlerChangeAll"
                                un-checked-children="关" v-model:checked="allCheck" />
                            <a-button style="margin:0 10px;" @click="handleGrouping" v-if="!isGrouping" type="primary">分组</a-button>
                            <a-button  style="margin:0 10px;" v-if="isGrouping" @click="handleChannlGrouping">取消</a-button>
                            <a-button  style="margin:0 10px;"  v-if="isGrouping" type="primary" @click="handleSureGrouping">确定</a-button>
                        </template>
                    </a-tabs>
                </div>
                <div class="duty-top-left-bottom">
                    <div class="tab-flex">
                        <a-card :title="item.seatName" v-for="item,index in seatData" style="width: 240px">
                            <template #extra>
                                <a-switch checked-children="开" un-checked-children="关" v-if="!isGrouping" v-model:checked="item.isUse" @change="switchhandlerChange(item)" />
                                <a-checkbox v-model:checked="item.isCheckTeam" v-else></a-checkbox>
                            </template>
                            <div class="card-content">
                                <Icon icon="mdi:account" size="100" v-if="!item.avatar"/>
                                <a-image :width="100" style="border-radius: 50%" :height="100"
                                    :src="getFileAccessHttpUrl(item.avatar)"
                                    v-else
                                    fallback="" />
                                <div class="card-ling" v-if="item.specialDetail.length > 0">
                                    <a-popover>
                                        <template #content>
                                            <div v-for="ytem,i in item.specialDetail">
                                                <p>{{ytem.realname}}</p>
                                                <p >{{ytem.startTime + ' - ' +ytem.endTime + ' '+ ytem.leaveType_dictText}}</p>
                                            </div>
                                           
                                        </template>
                                        <Icon icon="ri:alarm-warning-line" color="red"></Icon>
                                    </a-popover>
                                </div>
                                <div class="ellipsis" style="margin-top: 10px;">{{ item.realname || '人员名称' }}</div>
                                <div class="ellipsis" style="margin-top: 10px;">{{ item.roleName || '管制员资质名称'}}</div>
                            </div>
                            <!--判断这个席位是否有人-->
                            <template #actions v-if="item.realname">
                                <div class="card-bottom" v-if="item.onlineOrOff">
                                    <span class="card-bottom-label">在岗时长：</span>
                                    <span class="card-bottom-value">{{ item.onlineTime }}</span>
                                </div>
                                <div class="card-bottom " v-else>
                                    <span class="card-bottom-label ">离岗倒计时：</span>
                                    <span class="card-bottom-value card-bottom-red">{{item.offTimeLine}}</span>
                                </div>
                            </template>
                        </a-card>
                        <a-result v-if="seatData.length == 0" style="flex:1">
                            <template #icon>
                              <img :src="notDataSvg" width="150px" height="150px" >
                            </template>
                        </a-result>
                    </div>

                </div>
            </div>


            <div class="duty-top-right">
                <div class="duty-top-right-top">
                    <a-tabs v-model:activeKey="activeKey" @change="teamShiftChange">
                        <a-tab-pane v-for="item in dutyShiftList"  :key="item.value" :tab="item.label">
                        </a-tab-pane>
                    </a-tabs>

                </div>
                <div class="duty-top-right-bottom">
                    <CollapseContainer v-for="(value, key) in teamList">
                        <template #title>
                            {{ key ||''}}
                        </template>
                        <template #action>
                            <Popconfirm title="确定解散吗？" placement="topLeft" @confirm="handleDisband(value.length > 0 ? value[0]:{})">
                                <a href="#">解散</a>
                            </Popconfirm>
                        </template>
                        <div class="list-item" v-for="ytem in value">
                            <p class="duty-top-right-p ellipsis">{{ ytem.seatId_dictText + ( ytem.user?.realname ? ' | ' +  ytem.user?.realname :'')  }}</p> 
                            <Popconfirm title="确定要删除吗？" placement="topLeft" @confirm="handleDelete(ytem)">
                                <Icon style="display: inline-block;margin-left: auto;cursor: pointer;" icon="ri:delete-bin-5-line"></Icon>
                            </Popconfirm>
                        </div>
                    </CollapseContainer>
                    <a-result v-if="teamList.length == 0" style="flex:1">
                            <template #icon>
                              <img :src="notDataSvg" width="150px" height="150px" >
                            </template>
                    </a-result>

                </div>


               
                
                
            </div>
        </div>
        <div class="duty-bottom">
            <div class="duty-bottom-left">告警信息</div>
            <div class="duty-bottom-flex">

                <div class="duty-bottom-right">
                    <a-card :title="item.alarmTime" @click="showVideo(item)" v-for="item in alarmList" style="width: 240px;display: inline-block;">
                        <template #extra>
                            <span class="card-title">{{ item.alarmType }}</span>
                        </template>
                        <div class="card-content">
                            
                            <a-image :width="50" style="border-radius: 50%" :height="50" v-if="!item.isTeam && item.avatar"
                                :src="getFileAccessHttpUrl(item.avatar)"
                                :preview="false"
                                
                                fallback="" />
                            <Icon :size="50" icon="ri:team-fill"  v-if="item.isTeam"> </Icon>
                            <Icon icon="mdi:account" size="50" v-if="!item.avatar && !item.isTeam"/>
                                <div style="margin-left: 20px;">
                                <div class="ellipsis" style="margin-top: 10px; width: 120px;">{{ item.isTeam ? item.teamName : item.realname }}</div>
                                <div class="ellipsis"style="margin-top: 10px; width: 120px;">{{ item.isTeam ? item.userNames : item.roleName }}</div>
                            </div>

                        </div>
                    </a-card>
                     
                </div>
                <a-result v-if="alarmList.length == 0" style="flex:1">
                            <template #icon>
                              <img :src="notDataSvg" width="150px" height="150px" >
                            </template>
                </a-result>
            </div>
        </div>
        <a-modal v-model:open="open" title="席位分组" @ok="handleSeatTeamOk">
            <div style="padding: 20px;">
                <a-form
                    :model="formState"
                    name="basic"
                    ref="formRef"
                    :label-col="{ span: 8 }"
                    :wrapper-col="{ span: 16 }"
                    autocomplete="off"
                >
                <a-form-item
                    label="白夜班选择"
                    name="dutyShift"
                    :rules="[{ required: true, message: '请选择白夜班！' }]"
                    >
                    <JSearchSelect
                        placeholder="请选择白夜班"
                        v-model:value="formState.dutyShift"
                        style="width: 200px;"
                        dict="duty_shift">
                    </JSearchSelect>
                </a-form-item>
                <a-form-item
                    label="分组名称"
                    name="groupNames"
                    :rules="[{ required: true, message: '请填写分组名称！' }]"
                    >
                    <JSearchSelect
                        placeholder="请填写分组名称"
                        v-model:value="formState.groupNames"
                        @change="handleGroupName"
                        style="width: 200px;"
                        dict="group_names">
                    </JSearchSelect>
                </a-form-item>
                
                </a-form>
            </div>
        </a-modal>
        <ViolationModal @register="registerModal" @success="handleSuccess"></ViolationModal>
    </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref,h,reactive } from 'vue';
import { Icon } from '/@/components/Icon';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import dayjs from "dayjs";
import { Modal,message,Popconfirm } from 'ant-design-vue';
import { CollapseContainer } from '/@/components/Container';
import ViolationModal from './components/ViolationModal.vue'
import {JSearchSelect} from '/@/components/Form'
import {useModal} from '/@/components/Modal';
import {useDict} from '/@/hooks/jeecg/dictApi'
import { listAll,seatGroup,seatGroupSave,deleteGroup ,deleteGroupItem,forceCheckOut,enableSeat,forceCheckOutAll,enableSeatAll,
    ruleList,violationList
} from './dutyManagementList.api';
import { useUserStore } from '/@/store/modules/user';
import { GetListSeatUser} from '/@/api/sys/user';
import { VIOLATIONRULE_LEAVETEMP_TIME } from '/@/enums/ruleEnum';
import duration from 'dayjs/plugin/duration' // ES 2015
import { array } from 'vue-types';
import notDataSvg from '/@/assets/svg/no-data.svg';
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';
dayjs.extend(duration);
const [modal, contextHolder] = Modal.useModal();
const [registerModal, {openModal}] = useModal();
let activeKey = ref('');
let deptActiveKey = ref('');
let allCheck = ref(true);
let seatData = ref([]);
let intervalData = null;
let listInterVal = null;//请求席位定时器
let isGrouping = ref(false);//是否进行分组
let open = ref(false);//分组的确认弹出框
let seatTeamId = ref(null);
let postParam =  ref([]);//分组确定的数据
let alarmList  = ref([]);//告警数据
let openVideo = ref(false);//违规视频弹出框
let videoUrl  = ref(null);
let teamList = ref([]);//分组信息
let dutyShiftList = ref([])
let deptList  = ref([])//部门
const formRef = ref();
let groupName = ref('');
let ruleData  = ref([]);//规则数组
const formState = reactive({
    dutyShift: '',//值班班次
    groupNames: '',
    groupName:''
});
const userStore = useUserStore();
onMounted(async ()=>{
    let result = await listAll();
    result = result.filter(item =>{
        return item.izLeaf !=0
    })
    let data = result.map(item => {
        if(item.izLeaf !=0){
            return {
                label: item.departName,
                value: item.orgCode
            }
        }
    })

    if(data.length > 0){
        let obj = data.find(item=>{
            return item.value == userStore.getLoginInfo?.userInfo?.orgCode 
        })
        console.log("登录回来的数据",obj)
        if(obj){
            deptActiveKey.value = obj.value;
        }else{
            deptActiveKey.value = data[0].value;
        }
    }
    deptList.value = data;
    let rule =  await ruleList();
    if(rule.length){
        ruleData.value  = rule;
    }
    //TODO请求接口
    getSeatList();
    intervalData = setInterval(() => {
        updateSeatList();
   
    }, 1000);
    listInterVal= setInterval(() => {
        getSeatList();
        //获取告警信息
        getAlarmList();
    }, 60000);//每1分钟请求一次
    //获取告警信息
    getAlarmList();
    
    useDict('duty_shift').then((res)=>{
        dutyShiftList.value  = res;
        if(dutyShiftList.value.length > 0){
            activeKey.value = dutyShiftList.value[0].value;
            getTeamList();
        }
    });
    
    
})
const teamShiftChange = () =>{
    getTeamList();
}
function handleSuccess() {
}
const handleTab =() =>{
    if(listInterVal){
        clearInterval(listInterVal.value);
        listInterVal = null;
        listInterVal= setInterval(() => {
            getSeatList();
        }, 60000);//每1分钟请求一次
    }
    getSeatList();
    getTeamList();
    getAlarmList();
}
onUnmounted(()=>{
    if(intervalData){
        clearInterval(intervalData)
        intervalData = null;   
    }
    if(listInterVal){
        clearInterval(listInterVal)
        listInterVal = null;   
    }
})
const handleGroupName = (value,text)=>{
    formState.groupName = text
    groupName.value = text;
    console.log(text);
    
}
/**
 * 席位组合删除成员
 * @param item 
 */
const handleDelete = (item) =>{
    //TODO 调用接口删除某个席位。
    deleteGroupItem({
        id:item.id
    }).then((res)=>{
        getTeamList()
    })
}
/**
 * 解散分组
 * @param item 
 */
const handleDisband = (item) =>{
    //TODO 调用解散分组的接口
    deleteGroup({
        orgCode:item.orgCode,
        groupCode:item.groupCode,
        classType:item.classType
    }).then((res)=>{
        getTeamList()
    })
}
/**
 * 获取分组列表
 */
const getTeamList = () =>{
    seatGroup({
        orgCode:deptActiveKey.value,
        pageNo:1,
        pageSize:999,
        classType:activeKey.value
        
    }).then(res=>{
        console.log("分组：：",res);
        if(res.records.length){
            const groupByCategory = res.records.reduce((group, product) => {
                const { groupName } = product;
                console.log("==",group)
                group[groupName] = group[groupName] ?? [];
                group[groupName].push(product);
                return group;
            }, {});
            teamList.value = groupByCategory;
            console.log(groupByCategory);
        }else{
            teamList.value = []
        }
    })
}
const showVideo = (item)=>{
    // openVideo.value = true;
    // videoUrl.value = item.videoUrl
    console.log(item);
    
    openModal(true, {
       record:item.item,
       isUpdate: true,
       showFooter: false,
     });
}
/**
 * 获取告警信息
 */
const getAlarmList = ()=>{

    violationList({orgCode:deptActiveKey.value,pageSize:10,pageNo:1}).then(res=>{
        console.log("告警",res)
        if(res.records && res.records.length){
            let t = res.records.map(item=>{
                return {
                    avatar:item.avatar,
                    alarmTime:dayjs(item.violationTime).format("HH:mm"),
                    realname:item.userId_dictText,
                    alarmType:item.violationType_dictText,
                    roleName:item.roleName,
                    isTeam:item.groupViolation == 0 ? false :true,
                    teamName:item.groupName,//分组名称
                    videoUrl:'',//视频地址
                    item:item,
                }
            })
            alarmList.value = t;
        }else{
            alarmList.value = []
        }
    })
     
}
//保存分组信息
const handleSeatTeamOk = async () =>{
    try {
    const values = await formRef.value.validateFields();
        console.log('Success:', values);
        seatGroupSave({
            seatIdList:postParam.value,
            groupCode:values.groupNames,
            classType:values.dutyShift,
            orgCode:deptActiveKey.value,
            groupName:groupName.value
        }).then(res=>{
            open.value = false;
            isGrouping.value = false;
            console.log("进来了");
            
            reseatTeam();
            getTeamList()
        })
        //TODO 请求接口
     
    } catch (errorInfo) {
        console.log('Failed:', errorInfo);
    }
}
 
/**
 * 重置复选框
 */
const reseatTeam  = () =>{
    for(let item of seatData.value){
            if(!item.onlineOrOff){
                item.offTimeLine = offTimeFn(item);
                
            }
            item.isCheckTeam = false;//是否选中
    }
    console.log("kkkdddss====",seatData.value)
    seatData.value  = seatData.value;
}
/**
 * 取消分组
 */
const handleChannlGrouping = ()=>{
    seatData.value.forEach((item)=>{
        item.isCheckTeam = false;
    })
    isGrouping.value = false;
}
/**
 * 处理确定分组
 */
const handleSureGrouping =()=>{
    postParam.value = []
    for (const item of seatData.value) {
        if(item.isCheckTeam){
            postParam.value.push(
                item.seatId
            )
        }
    }
    if(postParam.value.length){
        open.value = true;
    }else{
        message.warning("请先勾选要分组的席位！")
    }
}
//离岗倒计时计算
const offTimeFn = (e)=>{
    let now = new Date().getTime();
    let allTime = e.offStartTime + e.offTime * 60 * 1000;
    let countdown = allTime - now ;
    let returnValue = ""
    if(countdown > 0){
        returnValue =  dayjs(countdown).format('mm分ss秒') 
    }else{
        returnValue = '已超时'
    }
    return returnValue
}
//定时修改离岗的倒计时
const updateSeatList=()=>{
    if(seatData.value.length > 0){
        for(let item of seatData.value){
            if(!item.onlineOrOff){
                item.offTimeLine = offTimeFn(item)
            }
        }
        seatData.value  = seatData.value;
    }
}
/**
 * 分组操作
 */
const handleGrouping = ()=>{
    isGrouping.value = true;
}
/**
 * 根据部门查询所有的席位
 */
const getSeatList =()=>{
    GetListSeatUser({orgCode:deptActiveKey.value,
        pageNo:1,
        pageSize:9999
    },'none').then((res)=>{
        console.log("席位列表",res)
        if(res.records.length > 0){
            let offTime = 0;//离岗规定时长（分钟）
            let obj = ruleData.value.find(item =>{
                return item.ruleKey == VIOLATIONRULE_LEAVETEMP_TIME
            })
            if(obj){
                offTime = obj.val;
            }
            let data = res.records.map((item)=>{
                return {
                    seatId:item.id,
                    avatar:item.user ? item.user.avatar : '',//人脸头像
                    realname:item.user ? item.user.realname : '人员名称',//人名称
                    roleName:(item.user && item.user.roleList.length) ? item.user.roleList[0].roleName: '管制员资质名称',//角色名称（资质名称）
                    seatName:item.name || '席位名称',
                    onlineOrOff:(item.userCheckIn && item.userCheckIn.checkOutTime) ? false:true ,//在岗或离岗
                    offTime:offTime,//离岗规定时长（分钟）
                    onlineTime:item.duration ? dayjs.duration(item.duration * 60 * 1000).format("HH时mm分"):'-时-分',//在岗时长
                    isUse:item.disable == 0 ? true:false,
                    offStartTime:(item.userCheckIn && item.userCheckIn.checkOutTime) ? dayjs(item.userCheckIn.checkOutTime).valueOf() : 0,
                    specialDetail:item.userLeaveList || []
                }
            })
            for(let item of data){
                if(!item.onlineOrOff){
                    item.offTimeLine = offTimeFn(item);
                    item.isCheckTeam = false;//是否选中
                }
            }
            seatData.value  = data;

        }else{
            seatData.value  = [];
        }
    })
    // setTimeout(()=>{
    //     let data = [{
    //         seatId:1,
    //         avatar:'',//人脸头像
    //         realname:'张三',//人名称
    //         roleName:'主班管制',//角色名称（资质名称）
    //         seatName:'主班管制席',//座席名称
    //         onlineOrOff:true,//在岗或离岗
    //         offTime:0,//离岗规定时长（分钟）
    //         onlineTime:'6时38分',//在岗时长
    //         isUse:true,//是否在使用
    //         offStartTime:1732540214000,//离岗开始时间
    //         specialDetail:[{ //特情
    //             realname:'张三',//人名称
    //             startTime:'09:00',//特情开始时间
    //             endTime:'10:00',//特情结束时间
    //             leaveType_dictText:'开会'//特情类型
    //         }],
    //         offTimeLine:''//
    //     },{
    //         seatId:2,
    //         avatar:'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    //         realname:'张三',
    //         roleName:'主班管制主班管制主班管制主班管制主班管制',
    //         seatName:'主班管制席',
    //         isUse:true,//是否在使用
    //         onlineOrOff:false,//在岗或离岗
    //         offTime:40,//离岗规定时长
    //         offStartTime:1732540214000,//离岗开始时间
    //         onlineTime:'6时38分',//在岗时长
    //         specialDetail:[],
    //         offTimeLine:''//
    //     }];
    //     for(let item of data){
    //         if(!item.onlineOrOff){
    //             item.offTimeLine = offTime(item);
    //             item.isCheckTeam = false;//是否选中
    //         }
    //     }
    //     seatData.value  = data;
        
    // },2000)
}
const switchhandlerChange = (item) =>{
    console.log(item);
    if(item.isUse){
        enableSeat({seatId:item.seatId}).then(res=>{
            getSeatList()
        })
    }else{
        forceCheckOut({seatId:item.seatId}).then(res=>{
            getSeatList()
        })
    }
    // forceCheckOut().then(res=>{

    // })
}
/**
 * 全部席位在线离线
 * @param e 
 */
const switchhandlerChangeAll = (e) => {
    let message = ""
    if(e){
        message = "确定要全部开启嘛？"
    }else{
        message = "确定要全部关闭嘛？"
    }
    Modal.confirm({
        title: message,
        icon: h(ExclamationCircleOutlined),
        onOk() {
            allCheck.value = e;
            //TODO请求接口
            let postData = [];
             if(e){
                enableSeatAll({
                    orgCode:deptActiveKey.value
                }).then(res=>{
                    getSeatList()
                })
             }else{
                forceCheckOutAll({
                    orgCode:deptActiveKey.value
                }).then(res=>{
                    getSeatList()
                })
             }
        },
        onCancel() {
            allCheck.value = !e;
        },
        class: 'test'
  });
    
   
    
    
}

</script>
<style lang="less" scoped>
html[data-theme='dark'] {
    .duty {
        background-color: #000;
    }

    .card-content {
        color: #fff !important;
    }

    .card-bottom-label {
        color: #fff !important;
    }
}

.duty {
    position: relative;
    height: 100%;
    padding: 0px 2px 0px 20px;
    background-color: #fff;
    box-sizing: border-box;
}

.duty-top {
    height: calc(100vh - 340px);
    width: 100%;
    display: flex;
    overflow:hidden;

    &-left {
        flex: 1;
        display: flex;
        position: relative;
        flex-direction: column;
        overflow: hidden;
        height: 100%;
        border-right: 1px solid #eeeeee;

        .duty-top-left-top {
            // position: absolute;
            display: flex;
            height: 50px;
            .top-tab {
                flex: 1;
            }
        }

        .duty-top-left-bottom {
            height: calc(100% - 50px);
            overflow-y: auto;
        }

        .tab-flex {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;

            .card-content {
                text-align: center;
                color: #000;
                position: relative;

                .card-ling {
                    position: absolute;
                    top: 0;
                    right: 0;
                }
                
            }

            .card-bottom {
                display: flex;
                padding: 0 20px;
                justify-content: space-between;

                .card-bottom-label {
                    font-weight: bold;
                    color: #000;
                }

                .card-bottom-value {
                    color: #018ffb;
                }

                .card-bottom-red {
                    color: red;
                }

            }
        }

        .flex-top-right {
            width: 100px;
            margin-left: auto;
        }
    }

    &-right {
        width: 240px;
        overflow: hidden;
        height: 100%;
        &-top{
            height: 50px;
            padding: 0 10px;
        }
        &-bottom{
            height: calc(100% - 50px);
            overflow-y: auto;
        }
        .list-item{
            display: flex;
            align-items: center;
        }
        &-p{
            
            border-bottom:1px solid #eeeeee;
            height: 30px;
            line-height: 30px;
            width: 200px;
        }
        p{
            margin-top: 0;
            margin-bottom: 0;
        }
    }
}

.duty-bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 20px 40px;
    height: 220px;

    border-top: 1px solid #eeeeee;

    .duty-bottom-left {
        position: absolute;
        left: 10px;
        font-weight: bold;
        width: 20px;
        top: 30%;
        margin-right: 20px;

    }

    .duty-bottom-flex {
        position: relative;
        display: flex;
        align-items: center;
        overflow-x: auto;

        .duty-bottom-right {
            display: flex;
            gap: 8px;

            .card-title {
                color: red;
            }

            .card-content {
                display: flex;
                align-items: center;
            }
        }
    }

}
.ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
</style>